﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IData_impl
{
    public sealed class Login_userDAL_impl : BaseDAL, ILogin_userDAL
    {
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public List<Login_user> GetAll_LoginUser()
        {
            string sql = "select * from login_user";
            var list = base.ExecSqlCmd(sql, null, cmd =>
             {
                 var reader = cmd.ExecuteReader();
                 if (!reader.HasRows)
                 {
                     return null;
                 }
                 List<Login_user> list = new List<Login_user>();
                 while (reader.Read())
                 {
                     Login_user login_User = new Login_user();
                     UserFieldMake(login_User, reader);
                     list.Add(login_User);
                 }
                 return list;
             });
            return list;
        }

        /// <summary>
        /// 根据账号，获取用户信息
        /// </summary>
        /// <param name="account">账号</param>
        /// <returns></returns>
        /// 创建时间：2022-11-23 09:16:06；作者：王浩力
        public Result<Login_user> GetLoginUser(string account)
        {
            //测试通过 //2023-1-11 15:41:28
//            //测试，新增字段；
//            string sql_table_alter = @" 
//alter table login_log add column 'test41'  int  default   1;
//alter table login_log add column 'test52'  int  default   5; ";
//            var kmssss = ExecSqlCmd(sql_table_alter, null, c =>
//            {
//                return c.ExecuteNonQuery();
//            });

            Dictionary<string, object> parames = new Dictionary<string, object>();
            parames.Add("$account", account);

            Login_user login_User = base.ExecSqlCmd("select * from login_user  where  User_account=$account "
                , parames
                , cmd =>
            {
                var reader = cmd.ExecuteReader();
                if (!reader.HasRows)
                {
                    return null;
                }
                if (reader.Read())
                {
                    Login_user login_User = new Login_user();
                    UserFieldMake(login_User, reader);
                    return login_User;
                }
                return null;
            });
            return new Result<Login_user>(login_User);
        }

        /// <summary>
        /// 根据主键获取用户
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        /// 创建时间：2022-11-23 09:17:42；作者：王浩力
        public Result<Login_user> GetLoginUserById(long id)
        {
            Dictionary<string, object> parames = new Dictionary<string, object>();
            parames.Add("$userId", id);

            Login_user login_User = base.ExecSqlCmd("select * from login_user  where  id=$userId ", parames, cmd =>
           {
               var reader = cmd.ExecuteReader();
               if (!reader.HasRows)
               {
                   return null;
               }
               if (reader.Read())
               {
                   Login_user login_User = new Login_user();
                   UserFieldMake(login_User, reader);
                   return login_User;
               }
               return null;
           });

            return new Result<Login_user>(login_User);
        }

        /// <summary>
        /// 用户字段封装
        /// </summary>
        /// <param name="login_User"></param>
        /// <param name="reader"></param>
        /// 创建时间：2022-11-23 09:20:34。作者：王浩力
        private static void UserFieldMake(Login_user login_User, System.Data.Common.DbDataReader reader)
        {
            login_User.Id = Convert.ToInt64(reader["id"]);
            login_User.User_real_name = reader["User_real_name"].ToString();
            login_User.User_account = reader["User_account"].ToString();
            login_User.Password_salt = reader["Password_salt"].ToString();
            login_User.Password_hash = reader["Password_hash"].ToString();
            login_User.Create_time = reader["Create_time"].ToString();
            login_User.Role_id = reader["Role_id"].ToString();
            login_User.Remark = reader["Remark"].ToString();
            login_User.U_stat = reader["U_stat"] == DBNull.Value ? (byte)0 : Convert.ToByte(reader["U_stat"]);
            login_User.SignatureImgPath = reader["SignatureImgPath"].ToString();
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="login_User"></param>
        /// <returns></returns>
        public Result UpdateLoginUser(Login_user login_User)
        {
            if (login_User == null)
            {
                return new Result("login_User不可为空");
            }
            if (login_User.Id < 1)
            {
                return new Result("Id参数无效");
            }
            var result = GetLoginUserById(login_User.Id);
            if (result.Data.Id < 1) return new Result("用户为空");

            //执行修改         
            string sql = @"update  login_user  
                 set  user_real_name=$user_real_name 
                       ,password_salt=$password_salt
                       ,password_hash=$password_hash
                       ,role_id=$role_id
                       ,remark=$remark
                       ,u_stat=$u_stat
                      where   id=$userId  ";

            Dictionary<string, object> parameDict = new Dictionary<string, object>();
            parameDict.Add("$userId", login_User.Id);
            parameDict.Add("$user_real_name", login_User.User_real_name);
            parameDict.Add("$password_salt", login_User.Password_salt);
            parameDict.Add("$password_hash", login_User.Password_hash);
            parameDict.Add("$role_id", login_User.Role_id);
            parameDict.Add("$remark", login_User.Remark);
            parameDict.Add("$u_stat", login_User.U_stat);

            int efCount = base.ExecSqlCmd(sql, parameDict, cmd =>
            {
                return cmd.ExecuteNonQuery();
            });
            if (efCount > 0)
            {
                return new Result("修改成功", 200);
            }

            return new Result("修改失败");
        }

        public Result AddUser(Login_user login_User)
        {
            string sql = @"INSERT INTO login_user (
                           id,
                           user_real_name,
                           user_account,
                           password_salt,
                           password_hash,
                           create_time,                        
                           remark,
                           u_stat
                       )
                       VALUES(
                           $id,
                           $user_real_name,
                           $user_account,
                           $password_salt,
                           $password_hash,
                           $create_time,                        
                           $remark,
                          1
                       );
            ";
            Result result = new Result("操作失败");
            Dictionary<string, object> parameDict = new Dictionary<string, object>();

            Snowflake snowflake = new Snowflake(1, 1);
            long id = snowflake.NextId();

            parameDict.Add("$id", id);
            parameDict.Add("$user_real_name", login_User.User_real_name);
            parameDict.Add("$user_account", login_User.User_account);
            parameDict.Add("$password_salt", login_User.Password_salt);
            parameDict.Add("$password_hash", login_User.Password_hash);
            parameDict.Add("$create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameDict.Add("$remark", login_User.Remark);

            int count = base.ExecSqlCmd(sql, parameDict, cmd =>
        {
            return cmd.ExecuteNonQuery();
        });
            if (count > 0)
            {
                result = new Result("新增成功", 200);
            }
            return result;
        }

        public Result UpdateColumn(long id, string column, object value)
        {
            if (string.IsNullOrWhiteSpace(column))
            {
                return new Result("column参数不可为空");
            }
            column = column.Replace("--", "");

            //执行修改         
            string sql = @$"update  login_user  
                 set  {column}=$columnValue                    
                      where   id=" + id;

            Dictionary<string, object> parameDict = new Dictionary<string, object>();
            parameDict.Add("$columnValue", value);

            int efCount = base.ExecSqlCmd(sql, parameDict, cmd =>
            {
                return cmd.ExecuteNonQuery();
            });
            if (efCount > 0)
            {
                return new Result("修改成功", 200);
            }

            return new Result("修改失败");
        }
    }
}
